In this article I will show how to append new data to an xml file using c#. If you want to add data to xml file without reloading the xml file appending data to the first row using the xElement addBeforeSelf and save xml file using the xDocument.
C# Code:
protected void Page_Load(object sender, EventArgs e)
{
if (File.Exists(Server.MapPath("Test.xml")) == false)
{
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = true;
xmlWriterSettings.NewLineOnAttributes = true;
using (XmlWriter xmlWriter = XmlWriter.Create(Server.MapPath("Test.xml"), xmlWriterSettings))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("School");
xmlWriter.WriteStartElement("Student");
xmlWriter.WriteElementString("FirstName", "Abdul");
xmlWriter.WriteElementString("LastName", "Rasik");
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
xmlWriter.Close();
}
}
else
{
XDocument xDocument = XDocument.Load(Server.MapPath("Test.xml"));
XElement root = xDocument.Element("School");
IEnumerable<XElement> rows = root.Descendants("Student");
XElement firstRow = rows.First();
firstRow.AddBeforeSelf(
new XElement("Student",
new XElement("FirstName", "mohamed"),
new XElement("LastName", "mohideen")));
xDocument.Save(Server.MapPath("Test.xml"));
}
}
Description: Run the application, if the XML file is not in the location, it will create a new xml file with name Test.xml. If xml file already exists, then it will append and overwrite the xml file.
Post your comments / questions
Recent Article
- How to create custom 404 error page in Django?
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
Related Article